//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package 力扣.题库.二分查找;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class demo_3488 {
    public demo_3488() {
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 3, 1, 4, 1, 3, 2};
        int[] queries = new int[]{0, 3, 5};
        System.out.println(solveQueries(nums, queries));
    }

    public static List<Integer> solveQueries(int[] nums, int[] queries) {
        HashMap<Integer, ArrayList<Integer>> map = new HashMap();
        int n = nums.length;

        for(int i = 0; i < n; ++i) {
            ArrayList<Integer> list = (ArrayList)map.getOrDefault(nums[i], new ArrayList());
            list.add(i);
            map.put(nums[i], list);
        }

        for(ArrayList<Integer> list : map.values()) {
            int begin = (Integer)list.get(0);
            int end = (Integer)list.get(list.size() - 1);
            list.add(0, end - n);
            list.add(begin + n);
        }

        List<Integer> res = new ArrayList();
        int qn = queries.length;

        for(int query : queries) {
            int num = nums[query];
            ArrayList<Integer> list = (ArrayList)map.get(num);
            if (list.size() == 3) {
                res.add(-1);
            } else {
                int l = 0;
                int r = list.size() - 1;

                while(l <= r) {
                    int mid = l + (r - l) / 2;
                    int p = (Integer)list.get(mid);
                    if (p == query) {
                        res.add(Math.min(p - (Integer)list.get(mid - 1), (Integer)list.get(mid + 1) - p));
                        break;
                    }

                    if (p < query) {
                        l = mid + 1;
                    } else {
                        r = mid - 1;
                    }
                }
            }
        }

        return res;
    }
}
